package org.xqh.utils.file;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.xqh.test.yzs.devicemonitor.ExportDeviceMonitor;
import org.xqh.test.yzs.devicemonitor.ExportDeviceMonitor.WarnLog;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @ClassName ReadTxtFileUtils
 * @Description 读取txt文件
 * @Author xuqianghui
 * @Date 2019/5/10 18:51
 * @Version 1.0
 */
@Slf4j
public class ReadTxtFileUtils {
    /**
     * 写入数据 到txt
     * @param content
     * @param filepath
     */
    public static void writeToFile(String content, String filepath){
        FileWriter fileWriter = null;
        try {
            fileWriter = new FileWriter(filepath);//创建文本文件
            fileWriter.write(content);//写入 \r\n换行
            fileWriter.flush();
        } catch (IOException e) {
            log.error("", e);
        }finally {
            try {
                fileWriter.close();
            } catch (IOException e) {
                log.error("", e);
            }
        }
    }

    /**
     * 写入数据 到txt
     * @param list
     * @param txtFile
     */
    public static void writeToTxt(List<String> list, String txtFile){
        FileWriter fileWriter = null;
        try {
            fileWriter = new FileWriter(txtFile);//创建文本文件
            for(String f:list){
                fileWriter.write(f+"\r\n");//写入 \r\n换行
            }
            fileWriter.flush();
        } catch (IOException e) {
            log.error("", e);
        }finally {
            try {
                fileWriter.close();
            } catch (IOException e) {
                log.error("", e);
            }
        }
    }

    /**
     * 读取txt文件
     * @param file
     * @return
     */
    public static List<String> readTxt(MultipartFile file) {
        try {
            return readByBytes(file.getBytes());
        } catch (IOException e) {
            log.error("", e);
        }
        return Lists.newArrayList();
    }

    /**
     * 读取txt文件
     * @param file
     * @return
     */
    public static List<String> readTxt(File file) {
        try {
            return readByBytes(FileUtils.readFileToByteArray(file));
        } catch (IOException e) {
            log.error("", e);
        }
        return Lists.newArrayList();
    }

    /**
     * 读取txt文件
     * @param file
     * @return
     */
    public static String readAllTxt(File file) {
        try {
            StringBuilder sb = new StringBuilder();
            List<String> txtList = readByBytes(FileUtils.readFileToByteArray(file));
            for(String line:txtList){
                sb.append(line);
                sb.append("\n");
            }
            return sb.toString();
        } catch (IOException e) {
            log.error("", e);
        }
        return null;
    }

    /**
     * 返回json内容
     * @param file
     * @return
     */
    public static String readJson(File file){
        StringBuilder sb = new StringBuilder();
        List<String> list = readTxt(file);
        list.stream().filter(s-> org.apache.commons.lang3.StringUtils.isNotBlank(s)).forEach(s-> {
            sb.append(s.trim());
        });
        return sb.toString();
    }

    public static Map<String, List<WarnLog>> dataMap = Maps.newConcurrentMap();


    public static void addLineTxt(String txt, long total, long cur){
        System.out.println("总记录: "+total +", 当前记录: "+cur + ", 内容: "+txt);
        txt = txt.replaceAll("None", "0").replaceAll("'", "\"");
        WarnLog log = JSON.parseObject(txt, WarnLog.class);
        if(Objects.nonNull(log) && StringUtils.hasText(log.getDeviceSn()) && ExportDeviceMonitor.deviceMap.containsKey(log.getDeviceSn())){
            log.setDeviceName("智能音箱");
            log.setSpaceName(ExportDeviceMonitor.deviceMap.get(log.getDeviceSn()));
            log.setLastHbTime(new Date(log.getUp_time() * 1000));
            if(!dataMap.containsKey(log.getDeviceSn())){
                List<WarnLog> list = Lists.newArrayList();
                list.add(log);
                dataMap.put(log.getDeviceSn(), list);
            }else {
                List<WarnLog> list = dataMap.get(log.getDeviceSn());
                WarnLog l = list.get(list.size() - 1);
                if(l.isFinish()){//如果上一条 记录 finish 那重新加一条
                     list.add(log);
                }else {
                    if(log.getUp_time() - l.getUp_time() > 120L){
                        if(l.isWarn()){
                            //如果上一条是异常 那么这次就是恢复
                            l.setRecoverTime(new Date(log.getCreateTime()));
                            l.setFinish(true);//标识为结束
                        }else {
                            //上一条是正常情况
                            l.setUp_time(log.getUp_time());
                            l.setWarnTime(new Date(l.getLastHbTime().getTime() + 120 * 1000));//设置异常时间
                            l.setWarn(true); // 设置为异常情况
                        }
                    }else {
                        if(l.isWarn()){
                             //如果上一条是异常 那么这次就是恢复
                            l.setRecoverTime(new Date(log.getCreateTime()));
                            l.setFinish(true);//标识为结束
                        }else {
                            l.setUp_time(log.getUp_time());
                            l.setLastHbTime(new Date(log.getUp_time() * 1000));
                        }
                    }
                }
            }
        }
    }



    /**
     *
     * @param filename 目标文件
     * @param charset 目标文件的编码格式
     */
    public static void readDaoxu(String filename, String charset) {
        RandomAccessFile rf = null;
        try {
            rf = new RandomAccessFile(filename, "r");
            long len = rf.length();
            long start = rf.getFilePointer();
            long nextend = start + len - 1;
            long total = nextend;
            String line;
            rf.seek(nextend);
            int c = -1;
            while (nextend > start) {
                c = rf.read();
                if (c == '\n' || c == '\r') {
                    line = rf.readLine();
                    if (StringUtils.hasText(line)) {
                        addLineTxt(new String(line.getBytes("ISO-8859-1"), charset), total, nextend);
                    } else {
                        System.out.println("333333=========="+line);
                    }
                    nextend--;
                }
                nextend--;
                rf.seek(nextend);
                if (nextend == 0) {// 当文件指针退至文件开始处，输出第一行
                    String t = new String(rf.readLine().getBytes("ISO-8859-1"), charset);
                    if(StringUtils.hasText(t)){
                        addLineTxt(t, total, nextend);
                    }
                }
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (rf != null)
                    rf.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    public static List<String> readByBytes(byte[] bytes){
        List<String> resList = Lists.newArrayList();
        InputStreamReader inputReader = null;
        BufferedReader bf = null;
        try {
            inputReader = new InputStreamReader(new ByteArrayInputStream(bytes));
            bf = new BufferedReader(inputReader);
            String lineTxt = null;
            while ((lineTxt = bf.readLine()) != null) {
                if(StringUtils.hasText(lineTxt)){
                    resList.add(lineTxt.trim());
                }
            }
        }catch (IOException e) {
            log.error("", e);
        }finally {
            try {
                if(null != inputReader){
                    inputReader.close();
                }
                if(null != bf){
                    bf.close();
                }
            } catch (IOException e) {
                log.error("", e);
            }
        }

        return resList;
    }



    /**
     *
     * @param filename 目标文件
     * @param charset 目标文件的编码格式
     */
    public static void read(String filename, String charset) {

        RandomAccessFile rf = null;
        try {
            rf = new RandomAccessFile(filename, "r");
            long len = rf.length();
            long start = rf.getFilePointer();
            long nextend = start + len - 1;
            String line;
            rf.seek(nextend);
            int c = -1;
            while (nextend > start) {
                c = rf.read();
                if (c == '\n' || c == '\r') {
                    line = rf.readLine();
                    if (line != null) {
                        System.out.println(new String(line
                                .getBytes("ISO-8859-1"), charset));
                    } else {
                        System.out.println(line);
                    }
                    nextend--;
                }
                nextend--;
                rf.seek(nextend);
                if (nextend == 0) {// 当文件指针退至文件开始处，输出第一行
                    // System.out.println(rf.readLine());
                    System.out.println(new String(rf.readLine().getBytes(
                            "ISO-8859-1"), charset));
                }
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (rf != null)
                    rf.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String args[]) {
        readDaoxu(ExportDeviceMonitor.work_path+"cdrv-20200814.txt", "UTF-8");
    }
}
